﻿using System.Collections.Generic;
using System.IO;

namespace SearchStringInTextFiles
{
    public class Program
    {
        private const string SourceFolderName = @".";
        private const string FileType = @".txt";
        private const string ResultsFile = @"";

        private static void SearchStringInFiles(string folderName, string str, string fileType, string resultsFile)
        {
            Queue<DirectoryInfo> nextDirs = new Queue<DirectoryInfo>();
            nextDirs.Enqueue(new DirectoryInfo(folderName));
            using (StreamWriter sw = new StreamWriter(resultsFile))
            {
                while (nextDirs.Count > 0)
                {
                    Queue<DirectoryInfo> currentDirs = nextDirs;
                    nextDirs = new Queue<DirectoryInfo>();
                    while (currentDirs.Count > 0)
                    {
                        DirectoryInfo dir = currentDirs.Dequeue();
                        foreach (DirectoryInfo d in dir.GetDirectories())
                        {
                            nextDirs.Enqueue(d);
                        }
                        foreach (FileInfo f in dir.GetFiles())
                        {
                            string line;
                            if (f.FullName.EndsWith(fileType) &&
                                f.Name != resultsFile &&
                                TryFindFirstMatchingLine(f, str, out line))
                            {
                                sw.WriteLine(f.FullName);
                                sw.WriteLine(line);
                                sw.WriteLine();
                            }
                        }
                    }
                }
            }
        }

        private static bool TryFindFirstMatchingLine(FileInfo file, string str, out string containingLine)
        {
            bool result = false;
            containingLine = null;
            using (StreamReader sr = new StreamReader(file.FullName))
            {
                while (!sr.EndOfStream)
                {
                    string line = sr.ReadLine();
                    if (line.Contains(str))
                    {
                        containingLine = line;
                        result = true;
                        break;
                    }
                }
            }
            return result;
        }

        public static void Main()
        {
            SearchStringInFiles(".", "This is cool.", ".txt", "results.txt");
        }
    }
}
